<?php
/**
 * Created by PhpStorm.
 * User: sunwu
 * Date: 2018/2/5
 * Time: 15:08
 */

namespace app\home\model;

use app\home\def\Status;

class Resource extends Base
{
    protected $pk = 'PK_ResourceGuid';
    protected $table = 'rs_resource';

    public function user()
    {
        return $this->belongsTo('user', 'FK_UserGuid', 'PK_UserGuid');
    }


    public function category()
    {
        return $this->belongsTo('resourceCategory', 'FK_ResourceCategoryGuid', 'PK_ResourceCategoryGuid');
    }


    public function rescomment()
    {
        return $this->hasMany('comment', 'FK_ResourceGuid');
    }

    public function getResource($guid = '', $limit = 1000)
    {
        if ($guid) {
            return self::with(['user', 'category', 'rescomment', 'rescomment.user'])->where(Status::$pass)->order("CreateTime desc")->limit($limit)->find($guid);
        } else {
            return self::with(['user', 'category', 'rescomment'])->order("CreateTime desc")->where(Status::$pass)->limit($limit)->select();
        }
    }

    /**
     * 过滤并获得ajax请求的资源数据
     * @param $data
     * @return array
     */
    public function getAjaxResData($data)
    {
        $returnArr = [];
        if (is_array($data)) {
            foreach ($data as $resData) {
                $t = [
                    'resguid' => $resData['PK_ResourceGuid'], //资源的guid
                    'userguid' => $resData['FK_UserGuid'],//用户的guid
                    'name' => $resData['user']['Name'],//资源拥有者姓名
                    'level' => $resData['user']['Level'],//用户等级
                    'cover' => $resData['user']['Cover'],//用户头像
                    'title' => $resData['Title'],//资源名称
                    'catname' => $resData['category']['Name'],//资源所属分类名称
                    'createTime' => $resData['CreateTime'],//资源创建时间`
                    'price' => $resData['Price'],//资源价格
                    'downloads' => $resData['Downloads'],//下载量,
                    'comments' => count($resData['rescomment'])//评论量
                ];
                $returnArr[] = $t;
            }
        }
        return $returnArr;
    }

    public function getResourceWithOrderAndLimit($order, $limit = 1000)
    {
        return self::with(['user', 'category', 'rescomment'])->order($order)->limit($limit)->order("CreateTime desc")->where(Status::status('pass'))->select();

    }
}